package com.xjl.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 控制线程执行完初始化的倒计时量打开门闸再执行下面的代码
 * 添加等待时间
 * CountDownLatch和CyclicBarrier都有让多个线程等待同步然后再开始下一步动作的意思，但是CountDownLatch的下一步的动作实施者是主线程，
 * 具有不可重复性；而CyclicBarrier的下一步动作实施者还是“其他线程”本身，具有往复多次实施动作的特点。
 * helloword版
 * @author xiaojinlu1990@163.com
 * date 2019-12-26
 */
@Slf4j
public class CountDownLatchExample1 {

    private final static int totleCount = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(totleCount);

        for (int i = 0; i < totleCount; i++) {
            int finalI = i;
            service.execute(() -> {
                waitThread(finalI);
                //每次减少一个
                countDownLatch.countDown();
            });
        }
        //添加等待时间
        countDownLatch.await(10,TimeUnit.MICROSECONDS);
        log.info("{}","finish!!!");

    }

    private static void waitThread(int finalI) {
        try {
            log.info("{}",finalI);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
